// ignore_for_file: deprecated_member_use

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:connectivity/connectivity.dart';
import 'package:flutter_widget/custom/custom_appbar.dart';

// ignore: must_be_immutable
class ConnetivityPage extends StatefulWidget {
  String name;
  ConnetivityPage({Key? key, required this.name}) : super(key: key);

  @override
  _ConnetivityPageState createState() => _ConnetivityPageState();
}

class _ConnetivityPageState extends State<ConnetivityPage> {
  String _connectionStatus = 'Unknown';
  late StreamSubscription subscription;
  @override
  void initState() {
    super.initState();
    subscription =
        Connectivity().onConnectivityChanged.listen(_updateConnectionStatus);
  }

  @override
  void dispose() {
    subscription.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: CustomAppbar(widget.name, Theme.of(context).primaryColor),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(_connectionStatus),
            const SizedBox(
              height: 30,
            ),
            ElevatedButton(
              onPressed: () async {
                final result = await Connectivity().checkConnectivity();
                _updateConnectionStatus(result);
              },
              child: Text(
                widget.name,
                style: const TextStyle(fontSize: 20, color: Colors.white),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Future<void> _updateConnectionStatus(ConnectivityResult result) async {
    switch (result) {
      case ConnectivityResult.wifi:
        setState(() => _connectionStatus = "wifi连接: ${result.toString()}");
        break;
      case ConnectivityResult.mobile:
        setState(() => _connectionStatus = "移动网诺连接: ${result.toString()}");
        break;
      case ConnectivityResult.none:
        setState(() => _connectionStatus = "无网诺连接: ${result.toString()}");
        break;
      default:
        setState(() => _connectionStatus = 'Failed to get connectivity.');
        break;
    }
  }
}
